const base = require("./../base");

module.exports = class extends base {
    async _initialize() {
        await super.isShopAuth();
    }

    async index() {
        const shopId = this.state.shop.id;
        const sku = await this.model("shop_sku")
            .query(qb => {
                qb.where("shop_id", shopId);
            })
            .fetchAll();
        this.success(this.getTree(sku));
    }

    /**
     *
     * @api {get} /shop/home/shop/product/sku/index 商品sku
     * @apiDescription 商品sku
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     *
     * @apiSampleRequest /shop/home/shop/product/sku/index
     *
     */
    async subIndex() {
        const { pid } = this.query;
        const shopId = this.state.shop.id;
        const shop = await this.model("shop_sku")
            .query(qb => {
                qb.where("shop_id", shopId);
                qb.where("pid", pid);
            })
            .fetchAll();
        this.success(shop);
    }

    async add() {
        const shopId = this.state.shop.id;
        const { skuData = [] } = this.post;

        for (const item of skuData) {
            const shopSku = await this.model("shop_sku")
                .query(qb => {
                    qb.where("shop_id", shopId);
                    qb.where("name", item.name);
                })
                .fetch();
            let pid = 0;
            if (!shopSku) {
                const _shopSku = await this.model("shop_sku")
                    .forge({
                        shop_id: shopId,
                        name: item.name
                    })
                    .save();
                pid = _shopSku.id;
            } else {
                pid = shopSku.id;
            }

            for (const inItem of item.value) {
                const shopInSku = await this.model("shop_sku")
                    .query(qb => {
                        qb.where("shop_id", shopId);
                        qb.where("pid", pid);
                        qb.where("name", inItem);
                    })
                    .fetch();
                if (!shopInSku) {
                    await this.model("shop_sku")
                        .forge({
                            shop_id: shopId,
                            pid: pid,
                            name: inItem
                        })
                        .save();
                }
            }
        }

        this.success();
    }
};
